package com.srwl.mytx.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.ListPopupWindow;

import com.alibaba.fastjson.JSONObject;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.srwl.easeui.domain.EaseEmojicon;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.activity.ChatRoomActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.domain.ImLatLng;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.im.ConversationService;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.im.PicSendThread;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.TextUtil;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ChatFileShowPageView;
import com.srwl.mytx.widget.ChatMessageListView;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.EaseVoiceRecorderView;
import com.srwl.mytx.widget.EaseVoiceRecorderView.EaseVoiceRecorderCallback;
import com.srwl.mytx.widget.KeyboardAwareRelativeLayout;
import com.srwl.mytx.widget.MyChatInputMenu;
import com.srwl.mytx.widget.chatRow.ChatRowAudioPlayer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.zibin.luban.Luban;


public class BaseChatFragment extends BaseFragment {
    protected static final String TAG = "BaseChatFragment";
    protected static final int REQUEST_CODE_MAP = 1;
    protected static final int REQUEST_CODE_PICTURE_CHOOSE = 4;
    private static final String MEDIA_TIPE = "amr";
    /**
     * params to fragment
     */
    protected Bundle fragmentArgs;
    protected String chatTargetId;
    protected String myId;
    protected ChatMessageListView messageListView;
    protected MyChatInputMenu inputMenu;


    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;

    protected Handler handler = new Handler();
    protected EaseVoiceRecorderView voiceRecorderView;
    static final int ITEM_TAKE_PICTURE = 1;
    protected int[] itemStrings = {R.string.attach_picture};
    protected int[] itemdrawables = {R.drawable.tx_chat_photo};
    protected int[] itemIds = {ITEM_TAKE_PICTURE};
    private boolean isMessageListInited;
    protected Dialog dialog;
    private ConversationService conversationService;
    protected Conversation conversation;
    // protected ShowBigImage showBigImage;
    protected ChatFileShowPageView photosView;
    protected List<Message> ywMessages;
    protected List<Message> imageMessageList = new ArrayList<>();
    protected Map<Integer, Integer> bigImageIndexMappingSmallImageIndex = new HashMap<>();//大图和小图索引 的映射
    protected User targetUser;
    public static boolean isVoiceAutoPlay;//标识语音信息是否自动播放,必须是public static 在MyChatRowVoice 中才能调用
    private KeyboardAwareRelativeLayout rootLayout;
    private Message targetMessage;//显示到消息列表中心的消息，以此消息为中心，上拉和下拉，加载两端的消息
    protected boolean hasNotch;

    public BaseChatFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.my_chat_fragment_layout, container, false);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        fragmentArgs = getArguments();
        targetUser = fragmentArgs.getParcelable(EaseConstant.EXTRA_TARGET_USER_INFO);
        targetMessage = fragmentArgs.getParcelable(Constant.EXTRA_INFO_MESSAGE);
        if (targetUser == null) {
            Log.e(TAG, "onActivityCreated: 聊天对象不能为空，，，，，，，，，，，，，，，，，，");
            return;
        }
        chatTargetId = targetUser.getuId();
        myId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
        initView();
        setUpView();
    }


    protected void initView() {

        View statusBar = getView().findViewById(R.id.status_bar);
        NotchScreenManager.getInstance().getNotchInfo(getActivity(), new INotchScreen.NotchScreenCallback() {
            @Override
            public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
                hasNotch = notchScreenInfo.hasNotch;
                Log.i(TAG, "Is this screen notch? " + hasNotch);
                if (hasNotch) {
                    //如果是刘海屏，不能设置 全屏（“沉浸模式”），否则视频不能填满屏幕
                    // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//此代码，在刘海屏手机使用，会让状态栏变为黑色，
                    statusBar.setVisibility(View.GONE);
                } else {
                    //如果不是刘海屏，就设置为全屏
                    SoftKeyboardFixerForFullscreen.assistActivity(getActivity());
                    setupStartBar();
                    int statusBarHeight = Utils.getStatusBarHeight(getActivity());
                    if (statusBarHeight != 0) {
                        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
                        layoutParams.height = statusBarHeight;
                        statusBar.setLayoutParams(layoutParams);
                    }
                }
            }
        });

        rootLayout = getView().findViewById(R.id.root_layout);
        final FrameLayout content = ((Activity) getContext()).findViewById(android.R.id.content);
        if (content != null) {
            rootLayout.setContentView(content.getChildAt(0));
        }
        voiceRecorderView = getView().findViewById(R.id.voice_recorder);
//        showBigImage = getView().findViewById(R.id.show_big_image);
//        showBigImage.setVisibility(View.GONE);
        photosView = getView().findViewById(R.id.photos_view);
        messageListView = getView().findViewById(R.id.message_list);
        messageListView.setListener(new ChatMessageListView.InteractionListener() {
            @Override
            public void onTouch() {
                hideSoftKeyboard();
            }
        });
        inputMenu = getView().findViewById(R.id.input_menu);
        registerExtendMenuItem();
        int keyboardHeight = rootLayout.getKeyboardHeight();
        Log.i(TAG, "initView: keyboardHeight  " + keyboardHeight);
        inputMenu.init(null, rootLayout);
        inputMenu.setChatInputMenuListener(new MyChatInputMenu.ChatInputMenuListener() {

            @Override
            public void onSendMessage(String content) {
                sendTextMessage(content);
            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderCallback() {
                    @Override
                    public void onVoiceRecordComplete(String audioPath, int voiceTimeLength) {
                        sendAudioMessage(audioPath, voiceTimeLength, MEDIA_TIPE);
                    }
                });
            }


            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {
                sendBigExpressionMessage(emojicon.getName(), emojicon.getIdentityCode());
            }
        });

        inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

        clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    protected void setUpView() {

        titleBar.setTitle(chatTargetId);
        titleBar.setTitle(targetUser.getUsername());
        titleBar.setRightImageResource(R.drawable.tx_right_menu_5);
        titleBar.setRightLayoutVisibility(View.VISIBLE);
        titleBar.titleLayout.setVisibility(View.VISIBLE);
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        titleBar.setRightLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                 //openMenu();
                showPopupWindow(getContext(), titleBar.getRightLayout());

            }
        });
        titleBar.titleView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
            }
        });
        initConversation();
        initMessageListView();
        isVoiceAutoPlay = Helper.getInstance().settingModel.getSettingVoiceAutoPlay();


    }


    protected int initBigImageData(int currentSmallImagePosition) {
        int currentBigImagePosition = 0;
        ywMessages = messageListView.getMessageList();
        imageMessageList.clear();
        bigImageIndexMappingSmallImageIndex.clear();
        //获取 大图和小图索引 的映射关系，放在一个map
        for (int i = 0; i < ywMessages.size(); i++) {
            Message message = ywMessages.get(i);
            Integer subType = message.getSubType();
            if (subType != null && (subType == Constant.IM_TYPE_IMAGE || subType == Constant.IM_TYPE_VIDEO)) {
                if (!Utils.isSendMessage(message)) {
                    Integer downloadState = message.getDownloadState();
                    if (downloadState != Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS) {
                        continue;
                    }
                }
                imageMessageList.add(message);
                if (currentSmallImagePosition == i) {
                    currentBigImagePosition = imageMessageList.size() - 1;
                }
                bigImageIndexMappingSmallImageIndex.put(imageMessageList.size() - 1, i);
            }
        }
        return currentBigImagePosition;
    }


    protected void registerExtendMenuItem() {
        for (int i = 0; i < itemStrings.length; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i]);
        }
    }


    protected void initConversation() {

        conversationService = IMSClientBootstrap.getInstance().getConversationService();
        conversation = conversationService.getC2cConversation(chatTargetId);

    }

    protected void initMessageListView() {

        if (targetMessage == null) {
            // 点击会话列表 进入聊天页面
            messageListView.initData(targetUser, conversation, rootLayout);
        } else {
            //通过搜索消息历史，进入聊天页面，携带了需要高亮显示的消息，将以此消息为消息列表的中心，展开
            messageListView.initData(targetUser, conversation, rootLayout, targetMessage);

        }
        isMessageListInited = true;

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //检查语音信息是否正在播放，如果在播放，应该中断播放，
        ChatRowAudioPlayer instance = ChatRowAudioPlayer.getInstance(getContext());
        if (instance.isPlaying()) {
            instance.breakPlay();
        }
        if (conversation != null) {
            conversation.clear();
        }
    }

    public void onBackPressed() {
        if (inputMenu.onBackPressed() && photosView.onBackPressed()) {
            getActivity().finish();

        }
    }


    //send message
    protected void sendTextMessage(String content) {
        Message message = new Message();
        message.setFromId(myId);
        message.setType(Constant.C2C_MESSAGE);
        message.setSubType(Constant.IM_TYPE_TEXT);
        message.setContent(content);
        conversation.sendMessage(message);
    }


    protected void sendBigExpressionMessage(String name, String identityCode) {
//        EMMessage message = EaseCommonUtils.createExpressionMessage(chatTargetId, name, identityCode);
//        sendMessage(message);
    }

    protected void sendAudioMessage(String filePath, int duration, String mimeType) {
        Message message = new Message();
        message.setFromId(myId);
        message.setType(Constant.C2C_MESSAGE);
        message.setSubType(Constant.IM_TYPE_AUDIO);
        message.setLocalFilePath(filePath);
        message.setPlayTime(duration);
        conversation.sendMessage(message);
    }

    /**
     * @param photos
     * @param isOriginal 是否原图发送
     */

    protected void sendImageMessage(ArrayList<Photo> photos, boolean isOriginal) {
        if (photos != null && !photos.isEmpty()) {
//            PicSendThread picSendThread = new PicSendThread(imagePaths, getActivity(), new PicSendThread.MessageSender() {
//                @Override
//                public void sendPicMessage(Message message) {
//                    message.setFromId(myId);
//                    conversation.sendMessage(message);
//                }
//            });
//
//            //如果是原图发送就不压缩
//            picSendThread.setNeedCompress(!isOriginal);
//            picSendThread.start();

            for (Photo photo : photos) {
                //因为android 10 不能直接以path 读取相册图片，所以先复制一份出来，方便自己app 调用处理
                String filePath = Helper.getInstance().getBasePath() + File.separator + photo.name;
                FileUtils.copyFile(getContext(), photo.uri, new File(filePath));
                try {
                    if (!isOriginal) {
                        File file = Luban.with(getActivity()).get(Helper.getInstance().getBasePath() + File.separator + photo.name);
                        filePath = file.getPath();
                    }
                    Message message = new Message();
                    message.setType(Constant.C2C_MESSAGE);
                    message.setSubType(Constant.IM_TYPE_IMAGE);
                    message.setFromId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                    message.setLocalFilePath(filePath);
                    message.setFromId(myId);
                    conversation.sendMessage(message);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    protected void sendVideoMessage(String videoPath) {

        Message videoMessage = new Message();
        videoMessage.setFromId(myId);
        videoMessage.setType(Constant.C2C_MESSAGE);
        videoMessage.setSubType(Constant.IM_TYPE_VIDEO);
        videoMessage.setLocalFilePath(videoPath);
        conversation.sendMessage(videoMessage);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
        ImLatLng latLng = new ImLatLng();
        latLng.setLatitude(latitude);
        latLng.setLongitude(longitude);
        latLng.setAddress(locationAddress);
        Message message = new Message();
        message.setFromId(myId);
        message.setType(Constant.C2C_MESSAGE);
        message.setSubType(Constant.IM_TYPE_GEO);
        message.setContent(JSONObject.toJSONString(latLng));
        conversation.sendMessage(message);
    }


    protected void sendFileMessage(String filePath) {
        Message message = new Message();

    }


    public void resendMessage(Message message) {
        conversation.reSendMessage(message);

    }

    /**
     * send file
     *
     * @param uri
     */
    protected void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;

            try {
                cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            Toast.makeText(getActivity(), R.string.File_does_not_exist, Toast.LENGTH_LONG).show();
            return;
        }
        //limit the size < 10M
        if (file.length() > 10 * 1024 * 1024) {
            Toast.makeText(getActivity(), R.string.The_file_is_not_greater_than_10_m, Toast.LENGTH_LONG).show();
            return;
        }
        sendFileMessage(filePath);
    }


    /**
     * clear the conversation history
     */
    protected void openMenu() {
//        String msg = getResources().getString(R.string.Whether_to_empty_all_chats);
//        new EaseAlertDialog(getActivity(), null, msg, null, new AlertDialogUser() {
//
//            @Override
//            public void onResult(boolean confirmed, Bundle bundle) {
//                if (confirmed) {
//                    EMClient.getInstance().chatManager().deleteConversation(chatTargetId, true);
//                    messageListView.refreshVideoItem();
//                }
//            }
//        }, true).show();
//

        //菜单 简单的，不能自定义布局
//        PopupMenu popupMenu=new PopupMenu(getContext(),titleBar);
//        popupMenu.getMenuInflater().inflate(,popupMenu.getMenu());


        View popView = getLayoutInflater().inflate(R.layout.chat_frgment_menu_layout, null);
        final PopupWindow popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.showAsDropDown(titleBar.getRightLayout(), Utils.dpToPx(-155, getContext()), Utils.dpToPx(3, getContext()), Gravity.END);
        View rl_voiceAutoPlay = popView.findViewById(R.id.rl_voice_auto_play);
        final TextView tv_voiceAutoPlay = popView.findViewById(R.id.tv_voice_auto_play);

        final Switch switch_voiceAutoPlay = popView.findViewById(R.id.switch_voice_auto_play);
        switch_voiceAutoPlay.setClickable(false);
        if (isVoiceAutoPlay) {
            switch_voiceAutoPlay.setChecked(true);
            tv_voiceAutoPlay.setText("关闭自动播放");
        } else {
            switch_voiceAutoPlay.setChecked(false);
            tv_voiceAutoPlay.setText("语音自动播放");
        }
        View rl_deleteChatRecord = popView.findViewById(R.id.rl_delete_chat_record);
        rl_voiceAutoPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isVoiceAutoPlay) {
                    isVoiceAutoPlay = false;
                    switch_voiceAutoPlay.setChecked(false);
                    tv_voiceAutoPlay.setText("语音自动播放");
                } else {
                    isVoiceAutoPlay = true;
                    switch_voiceAutoPlay.setChecked(true);
                    tv_voiceAutoPlay.setText("关闭自动播放");
                    messageListView.onAudioPlayCompletion(-1);//因为在这个方法里面，遍历消息的时候，会对传入的参数+1，作为索引开始遍历，传入一1，表示从0第一个开始遍历
                }

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        popupWindow.dismiss();
                    }
                }, 1500);
            }
        });
        rl_deleteChatRecord.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                //弹出提示对话框

                clearChatRecord();
            }
        });
        popView.findViewById(R.id.rl_to_user_profile).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                startActivity(new Intent(getActivity(), UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
            }
        });
    }

    private void showPopupWindow(final Context context, @NonNull View anchorView) {
        String OPEN_VOICE_AUTO_PLAY = "开启语音自动播放";
        String CLOSE_VOICE_AUTO_PLAY = "关闭语音自动播放";
        String CLEAR_CHAT_RECORD = "清空聊天记录";
        String TO_USER_PROFILE = "个人主页";
        List<String> popWindowItems = new ArrayList<>();
        if (isVoiceAutoPlay) {
            popWindowItems.add(CLOSE_VOICE_AUTO_PLAY);
        } else {
            popWindowItems.add(OPEN_VOICE_AUTO_PLAY);
        }
        popWindowItems.add(CLEAR_CHAT_RECORD);
        popWindowItems.add(TO_USER_PROFILE);
        final ListPopupWindow popupWindow = new ListPopupWindow(context);
        View popView = getLayoutInflater().inflate(R.layout.chat_frgment_menu_layout, null);
        popupWindow.setPromptView(popView);
       // popupWindow.setAdapter(new ArrayAdapter<String>(context, R.layout.simple_list_item, popWindowItems));
        popupWindow.setWidth(Utils.dpToPx(150, context));
        popupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
        popupWindow.setHorizontalOffset(Utils.dpToPx(-5, context));
        popupWindow.setVerticalOffset(Utils.dpToPx(3, context));
        popupWindow.setAnchorView(anchorView);//设置参照控件
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.tx_pop_bg_1));
        popupWindow.setDropDownGravity(Gravity.END);//设置对齐方式。
        popupWindow.setModal(true);//模态框，设置为true响应物理键
//        popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                popupWindow.dismiss();
//                String s = popWindowItems.get(position);
//                if (TextUtils.equals(s, OPEN_VOICE_AUTO_PLAY)) {
//                    isVoiceAutoPlay = true;
//
//                } else if (TextUtils.equals(s, CLOSE_VOICE_AUTO_PLAY)) {
//                    isVoiceAutoPlay = false;
//                } else if (TextUtils.equals(s, CLEAR_CHAT_RECORD)) {
//                    clearChatRecord();
//                } else if (TextUtils.equals(s, TO_USER_PROFILE)) {
//                    startActivity(new Intent(getActivity(), UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
//                }
//            }
//        });

        View rl_voiceAutoPlay = popView.findViewById(R.id.rl_voice_auto_play);
        final TextView tv_voiceAutoPlay = popView.findViewById(R.id.tv_voice_auto_play);

        final Switch switch_voiceAutoPlay = popView.findViewById(R.id.switch_voice_auto_play);
        switch_voiceAutoPlay.setClickable(false);
        if (isVoiceAutoPlay) {
            switch_voiceAutoPlay.setChecked(true);
            tv_voiceAutoPlay.setText("关闭自动播放");
        } else {
            switch_voiceAutoPlay.setChecked(false);
            tv_voiceAutoPlay.setText("语音自动播放");
        }
        View rl_deleteChatRecord = popView.findViewById(R.id.rl_delete_chat_record);
        rl_voiceAutoPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isVoiceAutoPlay) {
                    isVoiceAutoPlay = false;
                    switch_voiceAutoPlay.setChecked(false);
                    tv_voiceAutoPlay.setText("语音自动播放");
                } else {
                    isVoiceAutoPlay = true;
                    switch_voiceAutoPlay.setChecked(true);
                    tv_voiceAutoPlay.setText("关闭自动播放");
                    messageListView.onAudioPlayCompletion(-1);//因为在这个方法里面，遍历消息的时候，会对传入的参数+1，作为索引开始遍历，传入一1，表示从0第一个开始遍历
                }

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        popupWindow.dismiss();
                    }
                }, 1500);
            }
        });
        rl_deleteChatRecord.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                //弹出提示对话框

                clearChatRecord();
            }
        });
        popView.findViewById(R.id.rl_to_user_profile).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
            }
        });
        popupWindow.show();
    }

    private void clearChatRecord() {
        ConfirmDialog dialog = new ConfirmDialog(getActivity(), "提醒", getString(R.string.clear_all_records), true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                if (conversationService != null) {
                    conversationService.deleteConversation(conversation);
                }
            }
        });
        dialog.show();
    }


    public void onMediaButtonKeyEvent(int keyCode, KeyEvent event) {

        voiceRecorderView.OnMediaButtonKeyEvent(event, new EaseVoiceRecorderCallback() {
            @Override
            public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                sendAudioMessage(voiceFilePath, voiceTimeLength, MEDIA_TIPE);
            }
        });

    }


    /**
     * 设置为全屏，且状态栏为透明背景，
     * 字体显示为深色（6.0及以上）
     */
    protected void setupStartBar() {
        Window window = getActivity().getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//  全屏，状态栏字体黑色
        } else {
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
        window.setStatusBarColor(getResources().getColor(R.color.transparent));
    }
}
